package com.reider.log4AS3.core
{
	import com.reider.log4AS3.Logger;
	import com.reider.log4AS3.dataholder.Log;
	import com.reider.log4AS3.dataholder.LoggerScope;
	import com.reider.log4AS3.deciders.CachedTreeDecider;
	import com.reider.log4AS3.interfaces.ILoggerContext;
	import com.reider.log4AS3.interfaces.ILoggerScopeDecider;
	import com.reider.log4AS3.manager.LogManager;
	import com.reider.log4AS3.utils.ObjectContainer;
	
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;

	public class LoggerContext implements ILoggerContext
	{
		protected var loggers:Dictionary
		protected var loggerScopes:Array
		
		private var _decider:ILoggerScopeDecider
		
		public function get decider():ILoggerScopeDecider
		{
			if(!_decider){
				_decider = new CachedTreeDecider()
			}
			
			return _decider;
		}
		
		public function set decider(value:ILoggerScopeDecider):void
		{
			_decider = value;
		}
		
		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		
		public function LoggerContext()
		{
			loggers = new Dictionary()
		}
		
		//--------------------------------------------------------------------------
		//
		//  Public methods
		//
		//--------------------------------------------------------------------------

		public function addLog(log:Log):void
		{
			processLog( log )
		}
		
		public function setLoggerScopes(scopes:Array):void
		{
			loggerScopes = scopes
			decider.registerScopes( scopes )
		}
		
		public function getLogger(logTarget:Object):Logger
		{
			if(logTarget == null){
				throw new ArgumentError("logTarget must not be null")
			}
			var name:String
			
			if(logTarget is String){
				name = String(logTarget)
			}else{
				name = getQualifiedClassName(logTarget);
				name = name.replace(/::/g, ".");
			}
			
			var logger:Logger = new Logger(name, this);
			
			return logger;
		}
		
		//--------------------------------------------------------------------------
		//
		//  Protected methods
		//
		//--------------------------------------------------------------------------
		
		protected function processLog(log:Log):void
		{
			var scopes:Array = decider.getValidScopes( log.loggerName, log.level )
			if(scopes && scopes.length){
				for each(var scope:LoggerScope in scopes){
					scope.addLog( log )
				}
			}
		}
	}
}